package controllers

import (
	"encoding/json"
	beego "github.com/beego/beego/v2/server/web"
	"github.com/gorilla/websocket"
	"log"
	"net/http"
	"strconv"
	"sync"
	"week/common"
	"week/models"
)

type BarrageController struct {
	beego.Controller
}

type Message struct {
	GroupId       int    `json:"group_id" form:"group_id"`
	Content       string `json:"content" form:"content"`
	Video         int    `json:"video" form:"video"`
	EpisodesCount int    `json:"episodes_count" form:"episodes_count"`
}
type Node struct {
	Conn   *websocket.Conn
	Data   chan []byte
	Userid int
}

var ClientMap = make(map[int]*Node)
var wg sync.WaitGroup

func (b *BarrageController) Barrage() {
	Userid := b.GetString("userid")
	log.Println(Userid, "1111")
	upgrade := websocket.Upgrader{CheckOrigin: func(r *http.Request) bool {
		return true
	}}
	conn, err := upgrade.Upgrade(b.Ctx.ResponseWriter, b.Ctx.Request, nil)
	if err != nil {
		log.Println("websocket连接失败", err)
		return
	}
	id, _ := strconv.Atoi(Userid)
	node := &Node{
		Conn:   conn,
		Data:   make(chan []byte, 50),
		Userid: id,
	}
	ClientMap[id] = node
	wg.Add(2)
	go SendMsg(node)
	go ReadMsg(node)
	wg.Wait()
}
func SendMsg(node *Node) {
	defer wg.Done()
	for {
		_, message, err := node.Conn.ReadMessage()
		if err != nil {
			log.Println("获取消息失败")
			return
		}
		var msg Message
		json.Unmarshal(message, &msg)
		//todo: rabbitMQ生产者
		rabbitmq := common.NewRabbitMQSimple("" +
			"kuteng")
		rabbitmq.PublishSimple(msg.Content)
		group, _ := models.GetAnchorAll(models.AnchorList{
			AnchorId: msg.GroupId,
		})
		for _, v := range group {
			if node == ClientMap[v.Userid] {
				continue
			}
			log.Println(v.Userid)
			//
			friendMap, ok := ClientMap[v.Userid]
			if ok {
				friendMap.Data <- []byte(msg.Content)

			}
		}
		_, err = models.CreateBarrage(models.Barrage3{
			GroupId:       msg.GroupId,
			Userid:        node.Userid,
			VideoId:       msg.Video,
			EpisodesCount: msg.EpisodesCount,
			Content:       msg.Content,
		})
		if err != nil {
			node.Conn.WriteMessage(websocket.TextMessage, []byte("发送弹幕失败"))
			continue
		}
		//todo: rabbitMQ消费者
		rabbitmq = common.NewRabbitMQSimple("" +
			"kuteng")
		rabbitmq.ConsumeSimple(node.Conn)
	}
}
func ReadMsg(node *Node) {
	defer wg.Done()
	for {
		select {
		case data := <-node.Data:
			err := node.Conn.WriteMessage(websocket.TextMessage, data)
			if err != nil {
				log.Println("接收消息失败", err)
				return
			}
		}
	}
}
